package edu.university.demo.system.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;

import edu.university.demo.core.shiro.ShiroKit;
import edu.university.demo.system.entit.User;
import edu.university.demo.system.repository.UserDao;

/**
 * 用户管理类.
 * 
 * @author mayanping
 */
@Service
@Transactional
public class AccountService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final String MD5 = "MD5";
	public static final int HASH_INTERATIONS = 1024;

	private static Logger logger = LoggerFactory.getLogger(AccountService.class);

	@Autowired
	private UserDao userDao;
	private Clock clock = Clock.DEFAULT;

	public List<User> getAllUser() {
		return (List<User>) userDao.findAll();
	}

	public User getUser(Long id) {
		return userDao.findOne(id);
	}

	public User findUserByLoginName(String loginName) {
		return userDao.findByLoginName(loginName);
	}

	public void registerUser(User user) {
		entryptPassword(user);
		if(user.getLoginName().equals("admin")) {
			user.setRoles("admin");
		}else{
			user.setRoles("user");
		}
		user.setRegisterDate(clock.getCurrentDate());
		userDao.save(user);
	}

	public void updateUser(User user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			entryptPassword(user);
		}
		userDao.save(user);
	}

	public void deleteUser(Long id) {
		/*if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}*/
		userDao.delete(id);

	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {

		String hashAlgorithmName = MD5;
		Object credentials = user.getPlainPassword();
		//获得随机盐
		String saltStr = ShiroKit.getRandomSalt(5);
		user.setSalt(saltStr);
		
		Object salt = ByteSource.Util.bytes(saltStr);
		int hashIterations = HASH_INTERATIONS;
		Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
		user.setPassword(result.toString());
	}

	public void setClock(Clock clock) {
		this.clock = clock;
	}
}
